package cn.iocoder.yudao.module.wine.service.leaveinfo;

import cn.iocoder.yudao.framework.ip.core.utils.AreaUtils;
import cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils;
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
import cn.iocoder.yudao.module.wine.controller.app.leaveinfo.vo.AppLeaveInfoPageReqVO;
import cn.iocoder.yudao.module.wine.controller.app.leaveinfo.vo.AppLeaveInfoRespVO;
import cn.iocoder.yudao.module.wine.controller.app.userfans.enums.UserFansSubscribeEnum;
import cn.iocoder.yudao.module.wine.dal.dataobject.businessuser.BusinessUserDO;
import cn.iocoder.yudao.module.wine.dal.mysql.businessuser.BusinessUserMapper;
import cn.iocoder.yudao.module.wine.enums.BusinessUserEnum;
import cn.iocoder.yudao.module.wine.enums.LeaveInfoAuditEnum;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import org.springframework.validation.annotation.Validated;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

import cn.iocoder.yudao.module.wine.controller.admin.leaveinfo.vo.*;
import cn.iocoder.yudao.module.wine.dal.dataobject.leaveinfo.LeaveInfoDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.wine.dal.mysql.leaveinfo.LeaveInfoMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.wine.enums.ErrorCodeConstants.*;

/**
 * 发布离职通告 Service 实现类
 *
 * @author 管理员
 */
@Service
@Validated
public class LeaveInfoServiceImpl implements LeaveInfoService {

    //region 代码块
    @Resource
    private LeaveInfoMapper leaveInfoMapper;

    @Resource
    private MemberUserApi memberUserApi;

    @Resource
    private BusinessUserMapper businessUserMapper;
    //endregion

    @Override
    public Integer createLeaveInfo(LeaveInfoSaveReqVO createReqVO) {
        // 插入
        LeaveInfoDO leaveInfo = BeanUtils.toBean(createReqVO, LeaveInfoDO.class);
        leaveInfoMapper.insert(leaveInfo);
        // 返回
        return leaveInfo.getId();
    }

    @Override
    public void updateLeaveInfo(LeaveInfoSaveReqVO updateReqVO) {
        // 校验存在
        validateLeaveInfoExists(updateReqVO.getId());
        // 更新
        LeaveInfoDO updateObj = BeanUtils.toBean(updateReqVO, LeaveInfoDO.class);

        leaveInfoMapper.updateById(updateObj);
    }

    @Override
    public void deleteLeaveInfo(Integer id) {
        // 校验存在
        validateLeaveInfoExists(id);
        // 删除
        leaveInfoMapper.deleteById(id);
    }

    private LeaveInfoDO validateLeaveInfoExists(Integer id) {
        LeaveInfoDO leaveInfoDO = leaveInfoMapper.selectById(id);
        if (leaveInfoDO == null) {
            throw exception(LEAVE_INFO_NOT_EXISTS);
        }else {
            return leaveInfoDO;
        }
    }

    @Override
    public LeaveInfoDO getLeaveInfo(Integer id) {
        return leaveInfoMapper.selectById(id);
    }

    @Override
    public PageResult<LeaveInfoRespVO> getLeaveInfoPage(LeaveInfoPageReqVO pageReqVO) {
        return leaveInfoMapper.selectPage(pageReqVO);
    }

    @Override
    public PageResult<AppLeaveInfoRespVO>  getLeaveInfoList(AppLeaveInfoPageReqVO pageReqVO) {
        return leaveInfoMapper.selectLeaveInfoList(pageReqVO);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer appCreateLeaveInfo(LeaveInfoSaveReqVO createReqVO) {
        LeaveInfoDO leaveInfo = BeanUtils.toBean(createReqVO, LeaveInfoDO.class);
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        //查询会员信息
        MemberUserRespDTO user = memberUserApi.getUser(loginUserId);
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }
        BusinessUserDO businessUserDO = authBusinessUser();
        leaveInfo.setUserId(loginUserId);
        //判断用户是否剩余发布条数
        Integer leaveNum = businessUserDO.getLeaveNum();

        LocalDateTime createTime = user.getCreateTime();
        //获取下个月今天
        LocalDateTime plusMonthDateTime = createTime.plusMonths(1);
        if (plusMonthDateTime.isBefore(LocalDateTime.now())){
            //可发布数为0 抛出异常
            if (leaveNum.equals(0)) {
                throw exception(COUNT_ZERO);
            }
            if (leaveNum > 0) {
                //可发布数减1
                businessUserDO.setLeaveNum(businessUserDO.getLeaveNum() - 1);
                businessUserMapper.updateById(businessUserDO);
            }
        }

        //判断该用户发布的内容是否需要审核
        //if (AuditEnum.NO_AUDIT_REQUIRED.getCode().equals(user.getAudit())) {
        //    leaveInfo.setAudit(LeaveInfoAuditEnum.PASS_THE_AUDIT.getCode());
        //}
        //修改成发布投诉都需要审核09.01
        leaveInfo.setAudit(LeaveInfoAuditEnum.AUDIT.getCode());

        return leaveInfoMapper.insert(leaveInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void appUpdateLeaveInfo(LeaveInfoSaveReqVO updateReqVO) {
        LeaveInfoDO leaveInfo = BeanUtils.toBean(updateReqVO, LeaveInfoDO.class);
        LeaveInfoDO data = validateLeaveInfoExists(leaveInfo.getId());
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        //查询会员信息
        MemberUserRespDTO user = memberUserApi.getUser(loginUserId);

        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

        authBusinessUser();

        if (!data.getUserId().equals(loginUserId)){
            throw exception(HAVE_NO_RIGHT_LEAVE);
        }

        //if (AuditEnum.NO_AUDIT_REQUIRED.getCode().equals(user.getAudit())) {
        //    leaveInfo.setAudit(LeaveInfoAuditEnum.PASS_THE_AUDIT.getCode());
        //}else {
        //    leaveInfo.setAudit(LeaveInfoAuditEnum.AUDIT.getCode());
        //}

        //修改成发布投诉都需要审核09.01
        leaveInfo.setAudit(LeaveInfoAuditEnum.AUDIT.getCode());

        leaveInfoMapper.updateById(leaveInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void appDeleteLeaveInfo(Integer id) {
        // 校验存在
        LeaveInfoDO leaveInfoDO = validateLeaveInfoExists(id);
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();

        authBusinessUser();

        if (leaveInfoDO.getUserId().equals(loginUserId)){
            leaveInfoMapper.deleteById(id);
        }else {
            throw exception(HAVE_NO_RIGHT_LEAVE);
        }
    }

    @Override
    public List<AppLeaveInfoRespVO> getMyPublishLeaveInfoList(AppLeaveInfoPageReqVO pageReqVO) {
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        pageReqVO.setUserId(loginUserId);
        return leaveInfoMapper.getMyPublishLeaveInfoList(pageReqVO);
    }

    @Override
    public AppLeaveInfoRespVO appGetLeaveInfo(Integer id) {
        AppLeaveInfoRespVO data = leaveInfoMapper.getJoinById(id);
        LeaveInfoDO bean = BeanUtils.toBean(data, LeaveInfoDO.class);
        bean.setViewCount(bean.getViewCount() + 1);
        leaveInfoMapper.updateById(bean);
        String format = AreaUtils.format(data.getAreaId(), " ");
        data.setAreaName(format);

        //如果数据为空，说明未关注
        if (data.getSubscribeStatus() == null) {
            data.setSubscribeStatus(UserFansSubscribeEnum.UNFOLLOW.getStatus());
        }
        return data;
    }


    private BusinessUserDO authBusinessUser(){
        Long loginUserId = SecurityFrameworkUtils.getLoginUserId();
        BusinessUserDO businessUserDO = businessUserMapper.selectOne(new LambdaQueryWrapper<BusinessUserDO>().eq(BusinessUserDO::getUserId, loginUserId));
        if (businessUserDO == null) {
            throw exception(USER_NOT_EXISTS);
        }
        if(!BusinessUserEnum.AUDITED_STATUS.getCode().equals(businessUserDO.getStatus())){
            throw exception(BUSINESS_STATUS_AUDIT);
        }
//        if(!BusinessUserEnum.AUTHENTICATED_AUTH.getCode().equals(businessUserDO.getIsAuth())){
//            throw exception(BUSINESS_STATUS_AUTH);
//        }
        return businessUserDO;
    }
}
